import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import children from "./route";
import APP_CONFIG from "@/core/config";

const routes: RouteRecordRaw[] = [
  {
    path: "/",
    name: "layout",
    component: () => import("@/layouts/layout.vue"),
    children,
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

/** 当前路由栈 */
let routeStack: Array<string> = [];
/** 当前路由栈数量 */
let currRoutePostion = 0;
/** 路由前置守卫 */
router.beforeEach((to, from, next) => {
  next();
});
/** 路由后置守卫 */
router.afterEach((to, from) => {
  const { openTabbar, tabbar } = APP_CONFIG;
  const tabbarRouteNames = openTabbar? (tabbar?.tabbarList||[]).map(route=>route.name): []
  const { name } = to;
  const { position } = window.history.state;
  to.meta.transition =
    position >= currRoutePostion
      ? tabbarRouteNames.includes(String(from.name))
        ? ""
        : "slide-in"
      : "slide-out";
  /** 路由重定向 */
  if (position === currRoutePostion) {
    routeStack[Math.max(0, routeStack.length - 1)] = String(name);
  } else {
    const index = routeStack.indexOf(String(name));
    /** 后退到当前页面 */
    if (index >= 0) {
      routeStack = routeStack.slice(0, index + 1);
    } else {
      /** 前进到当前页面 */
      routeStack.push(String(name));
    }
  }
  //console.log("路由栈", routeStack);
  window.postMessage({ routeStack }, "*");
  currRoutePostion = position;
});

export default router;
